<template>
  <div class="bottom-view">
    <el-card shadow="hover" class="view">
      <template #header>
        <div>搜索关键词</div>
      </template>
      <div class="search-view">
        <div class="chart-wrap">
          <div class="chart">
            <div class="title">搜索用户数</div>
            <div class="count">{{ numberFormat(lineChartData.totalUser) }}</div>
            <v-chart :option="getLineOption('userList')"></v-chart>
          </div>
          <div class="chart">
            <div class="title">搜索量</div>
            <div class="count">
              {{ numberFormat(lineChartData.totalCount) }}
            </div>
            <v-chart :option="getLineOption('countList')"></v-chart>
          </div>
        </div>
        <div class="search-table">
          <el-table :data="tableData">
            <el-table-column label="排名" prop="rankNo"></el-table-column>
            <el-table-column label="关键字" prop="word"></el-table-column>
            <el-table-column label="搜索数量" prop="count"></el-table-column>
            <el-table-column label="搜索用户数" prop="user"></el-table-column>
            <el-table-column label="搜索占比数" prop="range"></el-table-column>
          </el-table>
          <el-pagination
            layout="prev, pager, next"
            :total="tableTotalData.length"
            v-model:currentPage="currentPage"
            v-model:page-size="pageSize"
          />
        </div>
      </div>
    </el-card>
    <el-card shadow="hover" class="view">
      <template #header>
        <div>分类销售排行</div>
        <el-radio-group v-model="radioSelect" size="small">
          <el-radio-button label="品类" />
          <el-radio-button label="商品" />
        </el-radio-group>
      </template>
      <div class="search-view">
        <v-chart :option="getPieOption()" autoresize></v-chart>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
export default {
  name: 'Keyword',
};
</script>
<script lang="ts" setup>
import * as echarts from 'echarts';
import type { EChartsType } from 'echarts';
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useReportDataStore } from '@/stores/reportData';
import useFormat from '@/hooks/useFormat';
const reportDataStore = useReportDataStore();
const { numberFormat, moneyFormat } = useFormat();
const currentPage = ref(1);
const pageSize = ref(5);
const radioSelect = ref('品类');
//准备数据
const searchWord = computed(() => reportDataStore.reportData.searchWord);

//获取分类销售排行
const saleRank = computed(() => reportDataStore.reportData.saleRank);

//表格列表要渲染的数据
const tableTotalData = computed(() => {
  if (!searchWord.value) return [];
  return searchWord.value.map((item, index) => ({
    ...item,
    rankNo: index + 1,
    range: ((item.user / item.count) * 100).toFixed(2) + '%',
  }));
});

//根据完整表格数据实现分页效果
const tableData = computed(() => {
  return tableTotalData.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  );
});

//准备需要的数据，数据来源于MockServer、data.json
const lineChartData = computed(() => {
  const data = {
    wordList: [] as string[], // 水平轴需要的数据
    userList: [] as number[], // 搜索用户数的Y轴使用的数据
    countList: [] as number[], // 搜索量图形Y轴要使用的数据
    totalUser: 0, // 总的搜索用户数
    totalCount: 0, //
  };

  if (tableTotalData.value && tableTotalData.value.length > 0) {
    tableTotalData.value.forEach((item) => {
      data.wordList.push(item.word),
        data.userList.push(item.user),
        data.countList.push(item.count),
        (data.totalUser += item.user),
        (data.totalCount += item.count);
    });
  }
  return data;
});
//装备表格上面的折线图的配置项数据
//准备两个折线图的样式基本上是一样的，只有数据不一样
const getLineOption = (listName: 'userList' | 'countList', name: string) => {
  return {
    xAxis: {
      boundaryGap: false, // 去掉两边留白
      data: lineChartData.value.wordList,
    },
    yAxis: {
      show: false,
    },
    series: {
      name,
      type: 'line',
      data: lineChartData.value[listName],
      // 曲线平滑
      smooth: true,
      areaStyle: {
        color: '#c7e7e7',
      },
      itemStyle: {
        opacity: 0,
      },
      lineStyle: {
        color: '#5FBBFF',
      },
    },
    grid: {
      left: 0,
      top: 0,
      bottom: 0,
      right: 0,
    },
  };
};

// 准备饼状图需要渲染时的数据
// 准备饼状图的数据
const pieChartData = computed(() => {
  const data = {
    categoryList: [] as any[], // 品类
    goodsList: [] as any[], // 商品
    cTotal: 0, // 分类的数量
    gTotal: 0, // 商品的数量
  };
  if (!saleRank.value) return {} as any;
  // 解构赋值
  const {
    category: { axisX, data1 },
    // 为了避免冲突 给下面的值取一个别名
    goods: { axisX: axisX2, data1: data2 },
  } = saleRank.value;
  const total1 = data1.reduce((prev, item) => prev + item, 0);
  data.cTotal = total1;
  const total2 = data2.reduce((prev, item) => prev + item, 0);
  data.gTotal = total2;

  axisX.forEach((item, index) => {
    const percent = ((data1[index] / total1) * 100).toFixed(2) + '%';
    data.categoryList.push({
      name: item + '|' + percent,
      value: data1[index],
      percent,
      labelName: item,
    });
  });

  axisX2.forEach((item, index) => {
    const percent = ((data2[index] / total2) * 100).toFixed(2) + '%';
    data.goodsList.push({
      name: item + '|' + percent,
      value: data2[index],
      percent,
      labelName: item,
    });
  });

  return data;
});

// 准备饼状图的配置项参数
const getPieOption = () => {
  const list =
    radioSelect.value === '品类'
      ? pieChartData.value.categoryList
      : pieChartData.value.goodsList;
  const total =
    radioSelect.value === '品类'
      ? pieChartData.value.cTotal
      : pieChartData.value.gTotal;
  return {
    title: [
      {
        text: `${radioSelect.value}分布`,
        textStyle: {
          fontSize: 14,
          color: '#666',
        },
        left: 20,
        top: 20,
      },
      {
        text: '累计订单量',
        subtext: total,
        textStyle: {
          fontSize: 14,
          color: '#999',
        },
        subtextStyle: {
          fontSize: 28,
          color: '#333',
        },
        left: '34.5%',
        top: '42.5%',
        textAlign: 'center',
      },
    ],

    tooltip: {
      // 整个图表项触发
      trigger: 'item',
      // 提示内容及样式
      formatter: (params: any) => {
        /* 
                        data: 当前项数据
                        marker: 内置提供的圆点标签
                        */
        // console.log('tt', params)
        return `${radioSelect.value}分布<br>
                  ${params.marker + params.data.labelName}<br>
                  ${params.marker}数量: ${params.data.value}<br>
                  ${params.marker}占比: ${params.data.percent}
                `;
      },
    },
    legend: {
      left: '70%',
      top: 'middle',
      // 排列方式
      orient: 'vertical',
      textStyle: {
        color: '#8c8c8c',
      },
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: ['35%', '50%'],
        center: ['35%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          // borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          // 在环的外侧
          position: 'outside',
          // show: false,
          // 指定特定标题
          formatter: function (params: any) {
            // console.log('ff', params)
            return params.data.labelName;
          },
        },
        // emphasis: {
        //   label: {
        //     show: true,
        //     fontSize: '40',
        //     fontWeight: 'bold'
        //   }
        // },
        // 标签的视觉引导线
        labelLine: {
          length: 7,
          length2: 5,
        },
        data: list,
      },
    ],
  };
};
</script>

<style lang="scss" scoped>
.bottom-view {
  display: flex;
  margin-top: 20px;

  .view {
    flex: 1;

    &:first-child {
      margin-right: 10px;
    }

    &:last-child {
      margin-left: 10px;
    }

    :deep(.el-card__header) {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 60px;
    }

    .search-view {
      height: 450px;
      display: flex;
      flex-direction: column;

      .chart-wrap {
        display: flex;

        .chart {
          flex: 1;

          &:first-child {
            margin-right: 5px;
          }

          &:last-child {
            margin-left: 5px;
          }

          .title {
            font-size: 14px;
            color: #999;
          }

          .count {
            font-size: 22px;
            color: #333;
            font-weight: 500;
            letter-spacing: 2px;
          }

          .echarts {
            height: 50px;
          }
        }
      }

      .search-table {
        flex: 1;
        margin-top: 20px;

        .el-pagination {
          text-align: right;
          margin-top: 10px;
        }
      }
    }
  }
}
</style>
